package com.tea.tea_vue.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tea.tea_vue.Entity.Goods;
import com.tea.tea_vue.Entity.News;
import com.tea.tea_vue.Mapper.GoodsMapper;
import com.tea.tea_vue.Mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodService {
    @Autowired
    private GoodsMapper goodsMapper;

    public String getGoodsList(Integer pageNum, Integer pageSize) throws JsonProcessingException, JSONException {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> goods = goodsMapper.selectAll();
        PageInfo<Goods> pageInfo = new PageInfo<>(goods, pageNum);
        ObjectMapper objectMapper = new ObjectMapper();
        String goodsList = objectMapper.writeValueAsString(goods);
        JSONArray jsonArray = new JSONArray(goodsList);
        JSONObject jsonPage = new JSONObject();
        jsonPage.accumulate("pageNum", pageNum);
        jsonPage.accumulate("pageCount", pageInfo.getPages());
        jsonArray.put(jsonPage);
        goodsList = jsonArray.toString();
        return goodsList;
    }
}
